package com.serializations;
/*

                  写字楼里写字间，写字间里程序员；
                  程序人'猿'写程序，又拿程序换酒钱。
                  酒醒只在网上坐，酒醉还来网下眠；
                  酒醉酒醒日复日，网上网下年复年。
                  但愿老死电脑间，不愿鞠躬老板前；
                  奔驰宝马贵者趣，公交自行程序员。
                  别人笑我忒疯癫，我笑自己命太贱；
                  不见满街漂亮妹，哪个归得程序'猿'？
━━━━━━神兽出没━━━━━━
 ┏┓   ┏┓
┏┛┻━━━┛┻┓
┃       ┃
┃   ━   ┃
┃ ┳┛ ┗┳ ┃
┃       ┃
┃   ┻   ┃
┃       ┃
┗━┓   ┏━┛
  ┃   ┃                    神兽保佑, 永无BUG!
  ┃   ┃       Code is far away from bug with the animal protecting
  ┃   ┗━━━┓
  ┃       ┣┓
  ┃       ┏┛
  ┗┓┓┏━┳┓┏┛
   ┃┫┫ ┃┫┫
   ┗┻┛ ┗┻┛
 */

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtobufIOUtil;
import io.protostuff.Schema;

/**
 * Created by 石头哥哥 on 11/16/15.
 * <p/>
 * server-service
 * <p/>
 * com.suweia.intellibox.server_service.common.suweiredis.serializations
 * <p/>
 * 使用:
 * this is lazily created and cached by RuntimeSchema
 * so its safe to call RuntimeSchema.getSchema(Foo.class) over and over
 * The getSchema method is also thread-safe
 * <p/>
 * Schema<User> schema = RuntimeSchema.getSchema(User.class);
 * User.Builder builder = User.newBuilder();
 * Schema<User> runtimeSchema = RuntimeSchema.getSchema(User.class);
 * <p/>
 * builder.setUsername("石头哥哥");
 * builder.setPwd("1233");
 * byte[] data_array = ProtoStufSer.toByteArray(builder.build(),runtimeSchema );
 * User _user = runtimeSchema.newMessage();
 * ProtoStufSer.mergeFrom(data_array, _user, schema);
 * <p/>
 * System.out.println(_user.getAge());
 * comments: 基于protosuf序列化 方案
 * 推荐使用该方案
 */
public class ProtoStufSer {

    /**
     * 讲对象序列化为字节数组
     *
     * @param object
     * @param runtimeSchema RuntimeSchema.getSchema(object.class)  , will be cache
     * @param <T>
     * @return
     */
    public static <T> byte[] toByteArray(T object, Schema<T> runtimeSchema) {
        LinkedBuffer buffer = LinkedBuffer.allocate(512);
        byte[] data_array = ProtobufIOUtil.toByteArray(object, runtimeSchema, buffer);
        buffer.clear();
        return data_array;
    }

    /**
     * 讲字节数组反序列化为对象
     * <p/>
     * object 将会被填充数据
     *
     * @param data          byte Array
     * @param object        =new Object()  or runtimeSchema.newMessage()
     * @param runtimeSchema runtimeSchema
     * @param <T>
     */
    public static <T> void mergeFrom(byte[] data, T object, Schema<T> runtimeSchema) {
        ProtobufIOUtil.mergeFrom(data, object, runtimeSchema);
    }

}
